package com.suxin.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;

/**
 * @Classname MyHttpServerHandler
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2021/1/3 20:42
 * @Created by ASUS
 *
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
 * HttpObject 客户端和服务器端互相通讯的数据 被封装成 HttpObject
 *
 */
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     *channelRead0 读取客户端数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 判断 msg 是不是 httpRequest 请求
        if (msg instanceof HttpRequest) {

            System.out.println("ChannelInitializer hashCode:--->" + this.hashCode() +
                    "   pipeline hashCode:--->" + ctx.pipeline().hashCode());

            System.out.println("msg 类型=" + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());

            HttpRequest request = (HttpRequest) msg;

            System.out.println(request.uri());

            if ("/favicon.ico".equals(request.uri())) {
                System.out.println("请求是 /favicon.ico，不做处理。。。");
                return;
            }

            // 回复给浏览器 [http 协议]
            ByteBuf buf = Unpooled.copiedBuffer("hello，我是服务器！", Charset.defaultCharset());
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, buf);
            httpResponse.headers()
                    .add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            httpResponse.headers()
                    .add(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            ctx.writeAndFlush(httpResponse);
        }

    }
}